<template>
    <div class="login-bac-container login-container">
        <div class="login-center">
            <div class="center-box-header" @click="toIndex">
                <h1 class="main-title hide"></h1>
                <h2 class="sub-title">欢迎进入商业世界</h2>
            </div>
            <div class="center-form">
                <el-tabs v-model="active">
                    <el-tab-pane label="登陆" name="login">
                        <el-form :rules="loginRules" :model="loginParams" ref="loginForm">
                            <el-form-item prop="phone">
                                <el-input placeholder="请输入手机号" v-model="loginParams.phone"/>
                            </el-form-item>
                            <el-form-item prop="password">
                                <el-input type="password" placeholder="请输入密码" v-model="loginParams.password"/>
                            </el-form-item>
                            <el-form-item prop="captcha">
                                <el-row>
                                    <el-col :span="15">
                                        <el-input placeholder="输入验证码" v-model="loginParams.captcha"/>
                                    </el-col>
                                    <el-col :span="7" :offset="1">
                                        <el-image :src="captchaUrl" @click="changeCaptchaUrl"
                                                  style="height: 40px;cursor: pointer;"></el-image>
                                    </el-col>
                                </el-row>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" style="width: 100%" @click="login" :loading="loginLoading">
                                    登陆
                                </el-button>
                                <div style="display: flex;justify-content: space-between;margin-top: 10px">
                                    <el-checkbox label="记住我" v-model="loginParams.rememberMe"></el-checkbox>
                                    <el-link :underline="false">忘记密码</el-link>
                                </div>
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                    <el-tab-pane label="注册" name="register">
                        <el-form :model="registerParams" ref="registerForm" :rules="registerRules">
                            <el-form-item prop="realName">
                                <el-input type="type" placeholder="请输入你的姓名" v-model="registerParams.realName"/>
                            </el-form-item>
                            <el-form-item prop="phone" ref="phone">
                                <el-input placeholder="请输入手机号" v-model="registerParams.phone"/>
                            </el-form-item>
                            <el-form-item prop="password">
                                <el-input type="password" placeholder="请输入密码" v-model="registerParams.password"/>
                            </el-form-item>
                            <el-form-item prop="validateCode">
                                <el-row>
                                    <el-col :span="15">
                                        <el-input placeholder="输入验证码" v-model="registerParams.validateCode"/>
                                    </el-col>
                                    <el-col :span="7" :offset="1">
                                        <el-button @click="getValidateCode">{{getValidateCodeTime == null ?
                                            '点击获取':getValidateCodeTime +'s后获取'}}
                                        </el-button>
                                    </el-col>
                                </el-row>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" style="width: 100%" @click="register"
                                           :loading="registerLoading">注册 赠送会员
                                </el-button>
                                <div style="display: flex;margin-top: 10px">
                                    <el-checkbox label="我已阅读并同意" v-model="read"></el-checkbox>
                                    <el-link :underline="false">《商友会使用条款》</el-link>
                                </div>
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                </el-tabs>
            </div>

        </div>
        <el-footer>

            <div class="login-footer">
                <span>广州土星科技责任有限公司所有</span>
                <span>粤多少号</span>
            </div>
        </el-footer>
    </div>

</template>
<script>
    import md5 from 'js-md5';

    export default {
        data: function () {

            // 手机号验证
            let checkPhone = (rule, value, callback) => {
                const phoneReg = /^1[3|4|5|6|7|8][0-9]{9}$/
                if (!value) {
                    return callback(new Error('手机号码不能为空'))
                }
                setTimeout(() => {
                    if (!Number.isInteger(+value)) {
                        callback(new Error('请输入数字值'))
                    } else {
                        if (phoneReg.test(value)) {
                            callback()
                        } else {
                            callback(new Error('手机号码格式不正确'))
                        }
                    }
                }, 100)
            }
            return {
                read: false,
                captchaUrl: '',
                active: 'login',
                getValidateCodeTime: null,
                loginLoading: false,
                registerLoading: false,
                loginParams: {
                    phone: "",
                    password: "",
                    captcha: "",
                    rememberMe: true,
                    timestamp:""
                },
                loginRules: {
                    phone: [
                        {validator: checkPhone, trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                        {min: 3, max: 10, message: '密码为3到10位', trigger: 'blur'}
                    ],
                    captcha: [
                        {required: true, message: '请输入验证码', trigger: 'blur'}
                    ]
                },
                registerParams: {
                    phone: "",
                    password: "",
                    realName: "",
                    validateCode: "",

                },
                registerRules: {
                    realName: [
                        {required: true, message: '请输入你的姓名', trigger: 'blur'},
                        {min: 2, max: 4, message: '长度为2到4位', trigger: 'blur'}
                    ],
                    phone: [
                        {validator: checkPhone, trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                        {min: 3, max: 10, message: '密码为3到10位', trigger: 'blur'}
                    ],
                    validateCode: [
                        {required: true, message: '请输入验证码', trigger: 'change'},
                        {min: 4, max: 4, message: '请输入4位验证码', trigger: 'change'}
                    ]
                },
            }

        },
        methods: {
            login() {
                this.$refs['loginForm'].validate((valid) => {
                    if (valid) {
                        this.loginLoading = true;
                        let newLoginParams = JSON.parse(JSON.stringify(this.loginParams));
                        newLoginParams.password = md5(this.loginParams.password)
                        this.$post("/user/login", newLoginParams).then((res) => {
                            this.loginLoading = false;
                            let token = res.data.token;
                            sessionStorage.setItem('token', token);
                            if (this.loginParams.rememberMe) {
                                sessionStorage.setItem("phone", this.loginParams.phone);
                            }
                            this.$notify({offset: 60, title: '成功', message: '登陆成功', type: 'success'});
                            this.$router.push("/")
                        }).catch(err => {
                            console.log(err)
                            this.loginLoading = false;
                            this.changeCaptchaUrl();
                        })
                    }
                });
            },
            register() {
                if (!this.read) {
                    this.$notify({title: '提示', message: '请阅读并同意《商友会使用条款》', type: 'error'});
                    return;
                }
                this.$refs['registerForm'].validate((valid) => {
                    if (valid) {
                        this.registerLoading = true;
                        let newRegisterParams = JSON.parse(JSON.stringify(this.registerParams));
                        newRegisterParams.password = md5(this.registerParams.password)
                        this.$post("/user/register", newRegisterParams).then((res) => {
                            this.registerLoading = false;
                            let token = res.data.token;
                            sessionStorage.setItem('token', token);
                            this.$router.push("/updateInfo")
                            this.$notify({offset: 60, title: '成功', message: '注册成功', type: 'success'});
                        }).catch(err => {
                            this.registerLoading = false;
                            console.log(err)
                        })
                    }
                });
            },
            changeCaptchaUrl() {
                this.loginParams.timestamp =  new Date().getTime();
                this.captchaUrl = this.$baseURL + '/user/captcha/getCaptcha?timestamp=' + this.loginParams.timestamp;
            },
            getValidateCode() {
                if (this.getValidateCodeTime != null) {
                    return;
                }
                this.$post("/user/getVerificationCodeTest", {phone: this.registerParams.phone}).then((res) => {
                    this.getValidateCodeTime = 60;
                    let inter = setInterval(() => {
                        this.getValidateCodeTime = this.getValidateCodeTime - 1;
                        if (this.getValidateCodeTime <= 0) {
                            clearInterval(inter);
                            this.getValidateCodeTime = null;
                        }
                    }, 1000);

                }).catch(err => {
                    console.log(err)
                })
            },
            toIndex() {
                // this.$router.push("/")
            }
        },
        created() {
            let phone = sessionStorage.getItem("phone");
            this.loginParams.phone = phone;
            this.changeCaptchaUrl();
            if (this.$route.query["active"] == 'login' || this.$route.query["active"] == 'register') {
                this.active = this.$route.query["active"];
            }

        }
    }
</script>
<style>
    .login-bac-container {
        background-image: url('../assets/images/login_bac.jpg');
        position: fixed;
        _position: absolute;
        top: 0;
        left: 0;
        height: 100%;
        width: 100%;
        min-width: 1000px;
        background-position: center 0;
        background-repeat: no-repeat;
        background-size: cover;
        -webkit-background-size: cover;
        -o-background-size: cover;
        zoom: 1;
    }

    .login-center {
        width: 400px;
        position: relative;
        top: 10%; /*偏移*/
        /*transform: translateY(-30%);*/
        margin: 0 auto;
    }

    .center-box-header {
        text-align: center;
    }

    .center-box-header .main-title {
        width: 160px;
        height: 74px;
        margin: 0px auto;
        background: url("../assets/images/logo.png") 0% 0% / contain no-repeat;
        background-position: center;
        cursor: pointer;
    }

    .center-box-header .sub-title {
        font-weight: 400;
        font-size: 18px;
        line-height: 1;
        margin: 10px 0px 20px;
        color: #fff;
    }

    .center-form {
        background-color: #fff;
        padding: 10px 30px 0px 30px;
        border-radius: 2px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        position: relative;
    }

    .center-form .el-tabs__nav-wrap::after {
        background-color: #fff;
    }

    .center-form .el-tabs__item {
        font-size: 16px;
        line-height: 45px;
        height: 45px;
        padding: 0;
        width: 72px !important;
        text-align: center;
    }

    .center-form .el-tabs__item.is-active {
        font-weight: 600;
        color: #333;
    }

    .center-form .el-tabs__active-bar {
        width: 72px !important;
    }

    .center-form .el-tabs__nav {
        float: none;
        margin: 0 100px;
    }

    .center-form .el-tabs__header {
        margin-bottom: 20px;
    }

    .center-form .el-form-item__content {
        line-height: 40px;
    }

    .center-form .el-alert {
        position: absolute;
        top: 55px;
        width: 352px;
    }

    .center-form .el-input__icon {
        font-size: 20px;
        line-height: 40px;
        margin-right: 10px;
    }

    /**
    底部
     */
    .login-footer {
        text-align: center;
        color: #fff;
        font-size: 14px;
        line-height: 30px;
        position: absolute;
        left: 0;
        right: 0;
        bottom: 0;
        margin: 0 auto;
    }

    .login-footer .el-link--inner {
        color: #fff;
        font-size: 14px;
        line-height: 30px;
    }

    .login-footer span {
        margin-right: 10px;
    }

</style>